﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace server.app.table
{
    public class Unit : Table<comm.objst.TableUnit>
    {
        public int AllUnitCount { get { return Orm.Count(); } }

        public Unit(World world)
            : base(Conf.TABLE_NAME_PREFIX + typeof(Unit).Name, world)
        {
        }

        public bool CreateUnit(comm.objst.TableUnit tableUnit)
        {
            return _world.DataManager.Call<bool>(sqlx =>
            {
                sqlx.BeginTxn();
                var r = CreateUnit(tableUnit);
                if (r)
                {
                    sqlx.CommitTxn();
                }
                return r;
            });
        }
        public bool CreateUnit(SQLx sqlx, comm.objst.TableUnit tableUnit)
        {
            return Orm.Insert(sqlx, tableUnit);
        }

        public int GetAllUnitCount(string playerId)
        {
            return _world.DataManager.Call<int>(sqlx =>
            {
                return (int)sqlx.ExecuteScalar("select count(*) from [" + _tableName + "] where [" + comm.objst.TableUnit.PLAYER_ID + "]=|0|", playerId);
            });
        }

        public comm.objst.TableUnit GetUnit(string unitId)
        {
            return _world.DataManager.Call<comm.objst.TableUnit>(sqlx =>
            {
                return GetUnit(unitId);
            });
        }
        public comm.objst.TableUnit GetUnit(SQLx sqlx, string unitId)
        {
            return Orm.GetObjectByKey(sqlx, unitId);
        }

        public comm.objst.TableUnit[] GetAllUnit(string playerId)
        {
            return Orm.GetList("select * from [" + _tableName + "] where [" + comm.objst.TableUnit.PLAYER_ID + "]=|0|", playerId);
        }
        public comm.objst.TableUnit[] GetAllUnit(string[] unitIds)
        {
            var sb = new StringBuilder();
            foreach (var unitId in unitIds)
            {
                sb.Append("'" + unitId + "',");
            }
            if (sb.Length > 0)
            {
                sb.Remove(sb.Length - 1, 1);
            }
            else
            {
                return new comm.objst.TableUnit[] { };
            }
            return Orm.GetList("select * from [" + _tableName + "] where [" + comm.objst.TableUnit.KEY_UNIT_ID + "] in (" + sb + ")");
        }
    }
}
